package com.atguigu.orderservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.utils.JwtUtils;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单管理 前端控制器
 * </p>
 *
 * @author kaixuan
 * @since 2020-06-13
 */
@Api(description = "订单管理")
@RestController
@RequestMapping("/orderservice/order")
//@CrossOrigin
public class TOrderController {

    @Autowired
    private TOrderService orderService;

    /**
     * 根据课程id和用户id创建订单
     * @param courseId 课程id
     * @param request 从请求中的token获取用户信息
     * @return
     */
    @ApiOperation("根据课程id和用户id创建订单")
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@ApiParam(value = "课程id",name = "courseId",required = true)@PathVariable String courseId, HttpServletRequest request) {
        boolean flag = JwtUtils.checkToken(request);
        if (!flag){
            return R.error().message("无效token");
        }else{
            String orderNo = orderService.createOrder(courseId, JwtUtils.getMemberIdByJwtToken(request));
            return R.ok().data("orderNo",orderNo);
        }
    }

    /**
     * 根据订单号获取订单信息
     * @param orderNo 订单号
     * @return
     */
    @ApiOperation("根据订单号获取订单信息")
    @GetMapping("getOrder/{orderNo}")
    public R getOrder(@ApiParam(value = "订单号",name = "orderNo",required = true)@PathVariable String orderNo){
        QueryWrapper<TOrder> query = new QueryWrapper<>();
        query.eq("order_no",orderNo);
        TOrder order = orderService.getOne(query);
        return R.ok().data("order",order);
    }


    /**
     * 根据用户id和课程id查询是否购买
     * @param memberId
     * @param courseId
     * @return
     */
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(@ApiParam(value = "用户id",name = "memberId",required = true)@PathVariable String memberId,
                               @ApiParam(value = "课程id",name = "courseId",required = true)@PathVariable String courseId){
        //订单状态是1表示支付成功
        int count = orderService.count(new QueryWrapper<TOrder>().eq("member_id", memberId).eq("course_id",courseId).eq("status", 1));
        if(count>0) {
            return true;
        } else {
            return false;
        }
    }
}

